package com.usian.wemedia.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.usian.common.fastdfs.FastDFSClientUtil;
import com.usian.model.common.dtos.PageResponseResult;
import com.usian.model.common.dtos.ResponseResult;
import com.usian.model.common.enums.AppHttpCodeEnum;
import com.usian.model.media.dtos.WmMaterialDto;
import com.usian.model.media.pojos.WmMaterial;
import com.usian.model.media.pojos.WmNewsMaterial;
import com.usian.model.media.pojos.WmUser;
import com.usian.utils.threadlocal.WmThreadLocalUtils;
import com.usian.wemedia.mapper.WmMaterialMapper;

import com.usian.wemedia.mapper.WmNewsMaterialMapper;
import com.usian.wemedia.service.WmMaterialService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;



import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class WmMaterialServiceImpl extends ServiceImpl<WmMaterialMapper, WmMaterial> implements  WmMaterialService{
    @Autowired
    private FastDFSClientUtil fastDFSClientUtil;

    @Autowired
    private WmNewsMaterialMapper wmNewsMaterialMapper;

    @Value("${fileServerUrl}")
    private String fileServerUrl;
    //素材上传
    @Override
    public ResponseResult upload(MultipartFile multipartFile) {
        try {
            if(multipartFile==null){
                return  ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
            }
            String path = fastDFSClientUtil.uploadFile(multipartFile);

            WmMaterial wmMaterial = new WmMaterial();
            wmMaterial.setUrl(path);
            wmMaterial.setIsCollection((short)0);
            //从本地线程获取用户id
            WmUser wmUser = WmThreadLocalUtils.getUser();
            if(wmUser!=null){
                wmMaterial.setUserId(wmUser.getId());

            }
            wmMaterial.setType((short)0);
            wmMaterial.setCreatedTime(new Date());
            this.save(wmMaterial);

            //返回前端url 要完整路劲
            wmMaterial.setUrl(fileServerUrl.concat(path));
            return ResponseResult.okResult(wmMaterial);

        }catch (Exception e){
            e.printStackTrace();
            return  ResponseResult.errorResult(AppHttpCodeEnum.SERVER_ERROR);
        }
    }

    //素材查询
    @Override
    public ResponseResult findList(WmMaterialDto dto) {
        if(dto==null){
            return  ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        dto.checkParam();


        //封装查询条件  userid   收藏
        LambdaQueryWrapper<WmMaterial> lambdaQueryWrapper =new LambdaQueryWrapper<>();

        WmUser wmUser = WmThreadLocalUtils.getUser();
        Integer userId =null;
        if(wmUser!=null){
            userId = wmUser.getId();
        }
        lambdaQueryWrapper.eq(WmMaterial::getUserId,userId);
        lambdaQueryWrapper.eq(WmMaterial::getIsCollection,dto.getIsCollection());

        //排序
        lambdaQueryWrapper.orderByDesc(WmMaterial::getCreatedTime);


        Page page = new Page(dto.getPage(), dto.getSize());
        IPage result = page(page,lambdaQueryWrapper);

        ResponseResult responseResult =new PageResponseResult(dto.getPage(),dto.getSize(),(int)result.getTotal());
        List<WmMaterial> records = result.getRecords();

        records = records.stream().map(a->{
            a.setUrl(fileServerUrl.concat(a.getUrl()));
            return a;
        }).collect(Collectors.toList());

        responseResult.setData(records);
        return responseResult;
    }

    //删除
    @Override
    public ResponseResult delMaterial(Integer id) {
        try {
            //1:检查参数
            if(id==null){
                return  ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
            }
            //2:校验素材是否被引用  素材表   素材关系表
            WmMaterial wmMaterial = this.getById(id);
            if(wmMaterial==null){
                return  ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
            }

            QueryWrapper<WmNewsMaterial> queryWrapper =new QueryWrapper<>();
            queryWrapper.lambda().eq(WmNewsMaterial::getMaterialId,id);
            Integer count = wmNewsMaterialMapper.selectCount(queryWrapper);
            if(count>0){
                return  ResponseResult.errorResult(AppHttpCodeEnum.NO_OPERATOR_AUTH);
            }
            //3:先删fastdfs上的图片
            String filepath =wmMaterial.getUrl().replaceAll(fileServerUrl,"");
            fastDFSClientUtil.delFile(filepath);
            //4：删素材库数据 物理删除
            boolean b = this.removeById(id);
            if(b){
                return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
            }else{
                return ResponseResult.errorResult(AppHttpCodeEnum.SERVER_ERROR);
            }
        }catch (Exception e){
            e.printStackTrace();
            return ResponseResult.errorResult(AppHttpCodeEnum.SERVER_ERROR);
        }
    }

    @Override
    public ResponseResult updateStatus(Integer id, Short status) {
        if(id==null ||status==null){
            return  ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        Integer userId=null;
        WmUser wmUser = WmThreadLocalUtils.getUser();
        if(wmUser!=null){
            userId = wmUser.getId();
        }

        UpdateWrapper<WmMaterial> updateWrapper=new UpdateWrapper<>();
        updateWrapper.lambda().set(WmMaterial::getIsCollection,status).eq(WmMaterial::getId,id).eq(WmMaterial::getUserId,userId);
        boolean b = this.update(updateWrapper);
        if(b){
            return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
        }else{
            return  ResponseResult.errorResult(AppHttpCodeEnum.SERVER_ERROR);
        }
    }
    }

